#include "config.h"
#include "app_wifi.h"
#include "app_mqtt.h"

void messageSend(String &topic, String &payload);

void messageReceived(String &topic, String &payload);

#define TOPIC_POST_DEVICE_DATA "/genghe/"+String(MQTT_USERNAME)+"/handler/"+String(ESP.getChipId())+"/postDeviceData"

void setWill()
{
    String topic = TOPIC_POST_DEVICE_DATA;
    mqttClient.setWill(topic.c_str(), R"({"state":"offline"})", true, 0);
}

void reportDevice()
{
    mqttClient.publish(TOPIC_POST_DEVICE_DATA, R"({"state":"online"})", true, 0);
}

void messageSend(String &topic, String &payload)
{
    mqttClient.publish(topic, payload);
}

void messageReceived(MQTTClient *client, char topic[], char bytes[], int length)
{
    Serial.write(bytes, length);
}

void app_setup()
{
    mqttClient.begin(MQTT_SERVER, MQTT_PORT, wiFiClient);
    mqttClient.onMessageAdvanced(messageReceived);
    setWill();
}

void app_loop()
{
    if (!mqttClient.loop())
    {
        wifi_connect(WIFI_SSID, WIFI_PASSWORD);
        print_wifi();
        mqtt_connect(MQTT_USERNAME, MQTT_PASSWORD);
        //TODO 订阅
        reportDevice();
    }
}
